package com.yanqu.road.server.timer;

import com.yanqu.road.entity.player.PlayerState;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.utils.executor.GeneralTask;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Comparator;
import java.util.List;

public class LogSaveTask extends GeneralTask {
    private static Logger logger = LogManager.getLogger(LogSaveTask.class);
    private static boolean running = false;

    @Override
    public void doRun() {
        if (!running) {
            running = true;
            try {
                LogMgr.save();
                List<GamePlayer> playerList = GamePlayerMgr.getCopyPlayerList();
                if (playerList.size() < 1000) {
                    return;
                }
                int num = 0;
                playerList.sort(new Comparator<GamePlayer>() {
                    @Override
                    public int compare(GamePlayer o1, GamePlayer o2) {
                        return Long.compare(o1.getLastPingTime(), o2.getLastPingTime());
                    }
                });
                for (GamePlayer player : playerList) {
                    long times = System.currentTimeMillis() - player.getLastPingTime();
                    if (player.getState() == PlayerState.OFFLINE && times > 10 * 60 *1000) {
                        GamePlayerMgr.onLogout(player, true);
                        num++;
                    }
                    if (num >= 300) {
                        break;
                    }
                }
            } catch (Exception e) {
                logger.error("save LogMgr error. ",e);
            }finally {
                running = false;
            }
        }
    }
}
